import { env } from '@/shared/constants';
import { CreationRatingDto, RatingDto } from '@/shared/interfaces/generated';
import { RootState } from '@/shared/store';
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

export const ratingApi = createApi({
  reducerPath: 'ratingApi',
  tagTypes: ['Rating'],
  baseQuery: fetchBaseQuery({
    baseUrl: env.apiUrl,
    prepareHeaders: async (headers, query) => {
      const authResult = (query.getState() as RootState).auth;
      if (authResult && authResult.accessToken) {
        headers.set('authorization', `Bearer ${authResult.accessToken}`);
      }
      headers.set('Request-Source', 'site');
      return headers;
    },
    credentials: 'include',
  }),
  endpoints: (builder) => ({
    getProductRatings: builder.query<{ ratings: RatingDto[] }, string>({
      query: (id) => ({
        url: `/products/${id}/ratings`,
      }),
      providesTags: ['Rating'],
    }),
    getSingleProductRating: builder.query<RatingDto, { productId: string; ratingId: string }>({
      query: ({ productId, ratingId }) => ({
        url: `/products/${productId}/ratings/${ratingId}`,
      }),
      providesTags: ['Rating'],
    }),
    addProductRating: builder.mutation<RatingDto, CreationRatingDto & { id: number }>({
      query: ({ id, rate, comment }) => ({
        url: `/products/${id}/ratings`,
        method: 'POST',
        body: {
          rate,
          comment,
        },
      }),
      invalidatesTags: ['Rating'],
    }),
    editProductRating: builder.mutation<RatingDto, CreationRatingDto & { id: number; ratingId: number }>({
      query: ({ id, rate, comment, ratingId }) => ({
        url: `/products/${id}/ratings/${ratingId}`,
        method: 'PATCH',
        body: {
          rate,
          comment,
        },
      }),
      invalidatesTags: ['Rating'],
    }),
    deleteProductRating: builder.mutation<RatingDto, { productId: string; ratingId: string }>({
      query: ({ productId, ratingId }) => ({
        url: `/products/${productId}/ratings/${ratingId}`,
        method: 'DELETE',
      }),
      invalidatesTags: ['Rating'],
    }),
  }),
});
